<?php defined('SYSPATH') or die('No direct script access.');

/**
 * 课时数据模型
 * 
 * @author 陈蕾
 */
class Model_Lesson extends ORM
{
	const TABLE = 'lesson';
	
	// Model table information
    protected $_table_name = 'lesson';
    
    // Table primary key and value
	protected $_primary_key  = 'id';
	protected $_primary_val  = 'name';
	
	// Validation members
    protected $_filters = array(
    	'chapter_id' => array(
    		'intval' => NULL
    	),
    	'client_id' => array(
    		'trim' => NULL
    	),
    	'name' => array(
    		'trim' => NULL,
    		'htmlspecialchars' => NULL,
    	),
    	'image' => array(
    		'trim' => NULL
    	),
    	'order' => array(
    		'intval' => NULL
    	)
    );
    
    protected $_rules = array(
        'chapter_id'=> array(
    		'not_empty' => NULL
    	),
        'name'=> array(
            'not_empty' => NULL,
            'max_length' => array('20')
        ),
        'client_id'=> array(
    		'not_empty' => NULL,
            'max_length' => array('10')
    	),
        'image'=> array(
            'max_length' => array('100')
        )
    );
    
    protected $_callbacks = array(
    	'chapter_id' => array(
    		array('Model_Lesson', 'verify_chapter_id')
    	),
    	'client_id' => array(
    		array('Model_Lesson', 'client_id_available')
    	)
    );
	
	/**
	 * 获取当前章节课时的下一课时
	 * 
	 * @return array 课时详细内容，否则为空数组
	 */
	public function getNext()
	{
		$record = DB::select()
			->from(self::TABLE)
			->where('chapter_id', '=', $this->chapter_id)
			->and_where('order', '>=', $this->order)
			->and_where('id', '!=', $this->id)
			->order_by('id', 'ASC')
			->execute()
			->current();
		
		if (!$record) {
			return array();
		}
		
		return $record;
	}
	
	//==========================================================================
	// 数据验证方法
	//==========================================================================
	
	/**
     * 判断章节ID是否有效
     */
	public static function verify_chapter_id(Validate $array, $field)
    {
        if (!Model_Chapter::exists($array[$field])) {
            $array->error($field, 'verify_chapter_id', array($array[$field]));
        }
    }
	
	/**
     * 判断客户端标识是否可用
     */
	public static function client_id_available(Validate $array, $field)
    {
    	$related = self::client_id_exists($array[$field]);
    	
    	if ($related) {
    		if (empty($array['id']) ||
    			$related != $array['id']) {
    			$array->error($field, 'client_id_available', array($array[$field]));
    		}
    	}
    }
    
	//==========================================================================
	// 静态方法
	//==========================================================================
	
     /**
     * 客户端标识是否已经存在
     */
	public static function client_id_exists($value)
    {
        return DB::select('id')
            ->from(self::TABLE)
            ->where('client_id', '=', $value)
            ->execute()
            ->get('id');
    }
    
    /**
     * 获取课时总数
     */
    public static function getCount()
    {
    	return DB::select(DB::expr('COUNT(*) AS total'))
			->from(self::TABLE)
			->execute()
			->get('total');
    }
    
    /**
     * 获取章节的第一个课时
     * 
     * @param int $chapter_id 章节ID
     */
	public static function getFirst($chapter_id)
	{
		$record = DB::select()
			->from(self::TABLE)
			->where('chapter_id', '=', $chapter_id)
			->order_by('order', 'ASC')
			->order_by('id', 'ASC')
			->limit(1)
			->execute()
			->current();
			
		if (!$record) {
			return array();
		}
		
		return $record;
	}
	
	/**
	 * 根据章节获取课时列表
	 * 
	 * @param int $chapter_id 章节ID
	 */
	public static function getListByChapter($chapter_id)
	{
		return DB::select()
			->from(self::TABLE)
			->where('chapter_id', '=', $chapter_id)
			->order_by('order', 'ASC')
			->execute()
			->as_array();
	}
	
	/**
	 * 获取各个章节的课时数量
	 * 
	 * @return 章节ID => 课时数量
	 */
	public static function getStats()
	{
		$records = DB::select('chapter_id', array(DB::expr('COUNT(*)'), 'count'))
			->from(self::TABLE)
			->group_by('chapter_id')
			->execute()
			->as_array();
		
		$count = array();
		foreach ($records as $record) {
			$key = $record['chapter_id'];
			$count[$key] = $record['count'];
		}
		
		return $count;
	}
}